package cn.itcast.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 虎哥
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {

    /**
     * 自定义过滤逻辑，拦截并判断用户的 access-token 是否等于 admin
     * @param exchange 上下文，包含各种你需要的东西
     * @param chain 过滤器链
     * @return 无
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取用户的request对象
        ServerHttpRequest request = exchange.getRequest();

        // 获取request对象中的 access-token 参数
        MultiValueMap<String, String> params = request.getQueryParams();
        String token = params.getFirst("access-token");

        // 判断参数值是否为 admin
        if ("admin".equals(token)) {
            // 符合，放行
            return chain.filter(exchange).then();
        }

        // 不符合，拦截
        // 得到response
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.FORBIDDEN);
        // 终止业务
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
